package com.qiall.gateway.service;

import com.qiall.boot.cache.ability.service.CacheService;
import com.qiall.common.exception.BusinessException;
import com.qiall.common.exception.ResultCode;
import com.qiall.gateway.service.dubborpc.DubboRpc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class InvokeDubboService {
    private ByteClassLoader byteClassLoader;

    public void initByteClassLoader(DubboRpc dubboRpc) {
        if (byteClassLoader == null) {
            byteClassLoader = ByteClassLoader.getInstance(dubboRpc);
            return;
        }
    }

    public Class<?> getDubboClass(String serviceName) {
        String key = serviceName.replaceAll("\\.", "/");
        Class<?> findBySingle = DubboClassLoaderClassSingleton.getInstance().get(key);
        if (findBySingle != null) {
            return findBySingle;
        }
        // 先搜索本地是否有
        try {
            Class<?> ret = Class.forName(serviceName);
            DubboClassLoaderClassSingleton.getInstance().put(key,ret);
            return ret;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        try {
            Class<?> classTmp = byteClassLoader.loadClass(serviceName);
            DubboClassLoaderClassSingleton.getInstance().put(key, classTmp);
            return classTmp;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        throw new BusinessException(ResultCode.SYSTEM_ERROR, "加载不到服务请检查api配置 是正确以及jar包是否为最新");
    }

}
